package com.youngjun.common.mybatis.autoconfigure;

import com.youngjun.common.util.IPUtils;
import com.youngjun.common.util.IdWorker;
import com.youngjun.common.util.SpringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author VirgoJun
 */
@Configuration
public class ApplicationConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SpringUtils springUtils(ApplicationContext applicationContext) {
        return SpringUtils.init(applicationContext);
    }

    @Bean
    public IdWorker idWorker() {
        String ipAddress = "127.0.0.1";
        try {
            ipAddress=IPUtils.getIp();
        }catch (Exception ignore){}
        long ip = IPUtils.ipV4ToLong(ipAddress);
        ip = ip % 256;
        long workerId = ip%31+1;
        long dataCenterId = ip/31+1;
        return new IdWorker(workerId, dataCenterId,1);
    }

}
